<template>
	<div>
		<el-upload
			action="#"
			list-type="picture-card"
			:data="extraParameters"
			:show-file-list="false"
			:before-upload="beforeUpload"
			:on-remove="handleRemove"
			:on-preview="handlePreview"
			:http-request="uploadImage">
			<img v-if="images" :src="images" class="avatar">
			<i v-else class="el-icon-plus"></i>
		</el-upload>
		
		<el-dialog :visible.sync="dialogVisible">
			<img width="100%" :src="images" alt="">
		</el-dialog>
	</div>
</template>
<script>
import { uploadImage } from '@/api/common/upload'
export default {
	name: 'singleUpload',
	props: {
		value: String,
		uploadType: String,
		acceptType:Array,
		//上传文件大小 默认5
		maxSize:{
			type: Number,
			default: 5
		},
		imageUrl:String
	},
	data(){
		return{
			extraParameters:{
				uploadType:this.uploadType
			},
			dialogVisible: false,
			images: this.imageUrl,
		}
	},
    methods: {
		emitInput(val) {
			console.log(val)
			this.$emit('input', val)
		},
		handleRemove() {
			this.emitInput('');
		},
		handlePreview() {
			this.dialogVisible = true;
		},
		beforeUpload(file) {
			const fileType = this.acceptType.indexOf(file.type) != '-1'
			const fileSize = file.size / 1024 / 1024 < this.maxSize;
			if(!fileType){
				this.$message.error('上传文件只能是'+this.acceptType+'格式!');
			}
			if (!fileSize) {
				this.$message.error('上传头像图片大小不能超过'+this.maxSize+'MB!');
			}
			return fileType && fileSize;
		},
		uploadImage(val){
			console.log(this.extraParameters)
			let formData = new FormData();
			formData.append('uploadType',this.extraParameters.uploadType)
			formData.append('files',val.file)
			uploadImage(formData).then(res =>{
				this.images = res.data.responseData[0]
				this.emitInput(res.data.responseData[0]);
			})
		}
    }
  }
</script>
<style>
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409EFF;
}

.avatar {
	border-radius: 6px;
	width: 148px;
	height: 148px;
	display: block;
}
</style>


